<!-- 商品发布 - 库存价格 -->
<template>
  <el-form ref="formRef" :disabled="isDetail" :model="formData" :rules="rules" label-width="120px">
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>素材设置 </span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px"> </span>
    </div>
    <el-form-item label="选择素材" prop="videos">
      <el-button @click="addFile()">关联素材</el-button>
      <div class="pl-10px">
        如果素材列表中没有你要的素材，请：前往
        <el-button @click="openForm('create')" link type="primary"> 添加素材</el-button>
      </div>
    </el-form-item>
    <el-form-item label="素材展示">
      <el-table :data="formData.videos" size="small" border>
        <el-table-column label="序号" align="center" width="50px" type="index" />
        <el-table-column label="素材标题" align="center" prop="title" width="180px" />
        <el-table-column label="素材封面" align="center" prop="picUrl" width="140px">
          <template #default="scope">
            <el-image :src="scope.row.picUrl" />
          </template>
        </el-table-column>
        <el-table-column label="素材内容" align="center" prop="videoUrl" width="140px">
          <template #default="scope">
            <div class="attachment-item mr-[10px] w-[120px]">
              <video :src="scope.row.videoUrl" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="收费状态" prop="name" align="center" width="100px">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              inline-prompt
              active-text="收费"
              inactive-text="免费"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100px">
          <template #default="scope">
            <el-button
              size="small"
              link
              style="color: #ff4d4f"
              @click="removeListener(scope.$index)"
              >移除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>价格设置 </span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px"> </span>
    </div>
    <section v-for="(item, index) in formData!.skus" :key="index">
      <el-form-item
        label="付费设置"
        :prop="`skus[${index}][tvSaleMethodType]`"
        :rules="rules.tvSaleMethodType"
      >
        <el-radio-group v-model="item.tvSaleMethodType">
          <el-radio :label="'免费'" :value="0"></el-radio>
          <el-radio :label="'付费'" :value="1"></el-radio>
        </el-radio-group>
      </el-form-item>
      <template v-if="item.tvSaleMethodType == 1">
        <el-form-item label="零售价" :prop="`skus[${index}][price]`" :rules="rules.price">
          <el-input-number
            v-model="item.price"
            :min="0"
            :precision="2"
            :step="0.1"
            :controls="false"
          >
            <template #suffix>
              <span>元</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item
          label="划线价"
          v-if="formData?.salesChannel?.includes(2)"
          :prop="`skus[${index}][marketPrice]`"
        >
          <el-input-number
            v-model="item.marketPrice"
            :min="0"
            :precision="2"
            :step="0.1"
            :controls="false"
          >
            <template #suffix>
              <span>元</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item
          label="最低价"
          v-if="formData?.salesChannel?.includes(1)"
          :prop="`skus[${index}][lowPrice]`"
        >
          <el-input-number
            v-model="item.lowPrice"
            :min="0"
            :precision="2"
            :step="0.1"
            :controls="false"
          >
            <template #suffix>
              <span>元</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="成本价" :prop="`skus[${index}][costPrice]`">
          <el-input-number
            v-model="item.costPrice"
            :min="0"
            :precision="2"
            :step="0.1"
            :controls="false"
          >
            <template #suffix>
              <span>元</span>
            </template>
          </el-input-number>
        </el-form-item>
      </template>
      <el-form-item label="有效期" :prop="`skus[${index}][expiryDate]`">
        <el-input v-model="item.expiryDate" class="w-150px!" :disabled="item.expiryDateUnit == 3">
          <template #append>
            <el-select v-model="item.expiryDateUnit" class="w-80px!">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.SPU_CARD_DATE_UNIT)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="库存" :prop="`skus[${index}][stock]`">
        <el-input-number v-model="item.stock" :controls="false" />
      </el-form-item>
    </section>
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>分销设置 </span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px">
        如商品仅有一个规格请使用单规格；如有容量、颜色等多种规格，请使用多规格。
      </span>
    </div>
    <el-form-item label="分销开关" props="subCommissionEnable">
      <el-switch
        v-model="formData.subCommissionEnable"
        @change="changeSubCommissionEnable"
      ></el-switch>
    </el-form-item>
    <el-form-item label="分销类型" props="subCommissionType" v-if="formData.subCommissionEnable">
      <el-radio-group
        v-model="formData.subCommissionType"
        class="w-80"
        @change="changeSubCommissionType"
      >
        <el-radio :value="false">默认设置</el-radio>
        <el-radio :value="true" class="radio">单独设置</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item v-if="formData!.subCommissionType">
      <section>
        <el-table :data="formData!.skus">
          <el-table-column align="center" label="一级返佣类型" min-width="168">
            <template #default="{ row }">
              <el-select
                v-model="row.firstBrokerageType"
                disabled
                placeholder="请选择返佣类型"
                class="w-100%!"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_SETTLEMENT_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="一级返佣" min-width="168">
            <template #default="{ row }">
              <el-input-number
                v-if="row.firstBrokerageType == 2"
                v-model="row.firstBrokeragePrice"
                :min="0"
                :precision="2"
                :step="0.1"
                class="w-100%!"
                :controls="false"
              >
                <template #suffix>
                  <span>元</span>
                </template>
              </el-input-number>
              <el-input
                v-if="row.firstBrokerageType == 1"
                v-model="row.firstBrokeragePercent"
                :max="100"
                :formatter="verifyNumberPercentage"
                :min="0"
                :precision="0"
                :step="1"
                class="w-100%!"
                :controls="false"
              >
                <template #suffix>
                  <span>%</span>
                </template>
              </el-input>
            </template>
          </el-table-column>

          <el-table-column align="center" label="二级返佣类型" min-width="168">
            <template #default="{ row }">
              <el-select
                v-model="row.secondBrokerageType"
                disabled
                placeholder="请选择返佣类型"
                class="w-100%!"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_SETTLEMENT_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column align="center" label="二级返佣" min-width="168">
            <template #default="{ row }">
              <el-input-number
                v-if="row.secondBrokerageType == 2"
                v-model="row.secondBrokeragePrice"
                :min="0"
                :precision="2"
                :step="0.1"
                class="w-100%!"
                :controls="false"
              >
                <template #suffix>
                  <span>元</span>
                </template>
              </el-input-number>
              <el-input
                v-if="row.secondBrokerageType == 1"
                v-model="row.secondBrokeragePercent"
                :formatter="verifyNumberPercentage"
                :max="100"
                :min="0"
                :precision="0"
                :step="1"
                class="w-100%!"
                :controls="false"
              >
                <template #suffix>
                  <span>%</span>
                </template>
              </el-input>
            </template>
          </el-table-column>
        </el-table>
      </section>
    </el-form-item>
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>销量设置</span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px">
        如商品在线下渠道有销售，可以填写该商品在线下渠道的销售数据。线上展示销量数据为线下销量+线上销量之和。
      </span>
    </div>
    <el-form-item label="线下销量" prop="virtualSalesCount">
      <el-input-number
        v-model="formData.virtualSalesCount"
        @change="virtualSalesCountChange"
        :min="0"
        placeholder="请输入线下销量"
      />
    </el-form-item>
  </el-form>

  <!-- 表单弹窗：添加/修改 -->
  <MaterialForm ref="materialFormRef" />
  <!-- 素材选择 -->
  <MaterialTableSelect ref="FileSelectRef" :multiple="true" @change="setFile" />
</template>
<script lang="ts" setup>
import { PropType } from 'vue'
import {
  copyValueToTarget,
  fenToYuan,
  floatToFixed2,
  generateNumericUUID,
  yuanToFen
} from '@/utils'
import { propTypes } from '@/utils/propTypes'
import { getPropertyList, PropertyAndValues } from '@/views/mall/product/spu/components/index'
import type { Spu } from '@/api/mall/product/spu'
import { img } from '@/utils/common'
import MaterialForm from '@/views/mall/material/MaterialForm.vue'
import MaterialTableSelect from '@/views/mall/material/MaterialFormTableSelect.vue'

import { verifyNumberPercentage } from '@/utils/formatter'

import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'

defineOptions({ name: 'ProductSpuActivitySkuForm' })
const { t } = useI18n() // 国际化

const message = useMessage() // 消息弹窗

const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  isDetail: propTypes.bool.def(false), // 是否作为详情组件
  activeName: propTypes.string.def('sku')
})
const formRef = ref() // 表单 Ref
const propertyList = ref<PropertyAndValues[]>([]) // 商品属性列表
const formData = reactive<Spu>({
  spuType: 3,
  specType: false, // 商品规格
  salesChannel: [],
  virtualSalesCount: 0,
  subCommissionType: false, // 分销类型
  subCommissionEnable: false, //分销开关
  videos: [], //视频素材
  skus: [
    {
      tvSaleMethodType: 0, //售卖方式类型 0 免费 1 收费 2 加密
      price: undefined, // 商品价格
      skuType: 34, //商品属性
      stock: 1,
      firstBrokeragePercent: 0, // 一级分销的佣金 比例
      secondBrokeragePercent: 0, // 二级分销的佣金 比例
      firstBrokerageType: 2, // 一级分销的佣金类型
      secondBrokerageType: 2, // 二级分销的佣金类型
      firstBrokeragePrice: 0, // 一级分销的佣金
      secondBrokeragePrice: 0, // 二级分销的佣金
      skuId: generateNumericUUID() //商品 SKU 编号
    }
  ]
})
/**虚拟销量 */
const virtualSalesCountChange = () => {
  Object.assign(props.propFormData, formData)
}
/** 分销类型 */
const changeSubCommissionEnable = () => {
  formData.subCommissionType = false
  Object.assign(props.propFormData, formData)
}
const changeSubCommissionType = () => {
  // 默认为零，类型切换后也要重置为零
  for (const item of formData.skus!) {
    item.firstBrokeragePrice = 0
    item.secondBrokeragePrice = 0
  }
  Object.assign(props.propFormData, formData)
}
const rules = reactive({
  tvSaleMethodType: [required],
  stock: [required],
  price: [required],
  number: [required],
  videos: [required]
})

// ================= 商品选择相关 =================
export interface DiscountProductVO {
  spuId: number
  skuId: number
  discountPrice?: number
  discountPercent?: number
  activityProductLowPrice?: number
  discountType: number
  selected: boolean
  activityProductCount: number
}

// ================= end =================
onMounted(() => {})
/** 将传进来的值赋值给 formData */

watch(
  () => props.propFormData,
  async (data) => {
    if (!data) {
      return
    }

    copyValueToTarget(formData, data)
    // 将 SKU 的属性，整理成 PropertyAndValues 数组
    propertyList.value = getPropertyList(data)
  },
  {
    deep: true,
    immediate: true
  }
)

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    await unref(formRef).validate()

    // 校验通过更新数据
    Object.assign(props.propFormData, formData)
  } catch (e) {
    message.error('【活动信息】不完善，请填写相关信息')
    emit('update:activeName', 'sku')
    throw e // 目的截断之后的校验
  }
}
/** 素材管理*/
/** 添加/修改操作 */
const materialFormRef = ref()
const openForm = (type: string, id?: number) => {
  materialFormRef.value.open(type, id)
}
const FileSelectRef = ref()
// 素材选中
const addFile = () => {
  FileSelectRef.value.open(formData.videos)
}
const setFile = (fileList) => {
  console.log(fileList)
  formData.videos = fileList.map((el) => {
    return {
      title: el.title,
      picUrl: el.picUrl,
      videoUrl: el.videoUrl,
      // sort: el.sort,
      status: true,
      id: el.id
    }
  })
  Object.assign(props.propFormData, formData)
}
// 移除素材
const removeListener = (listener, index?) => {
  console.log(listener, 'listener')
  ElMessageBox.confirm('确认移除该素材吗？', '提示', {
    confirmButtonText: '确 认',
    cancelButtonText: '取 消'
  })
    .then(() => {
      formData.videos.splice(index, 1)
      Object.assign(props.propFormData, formData)
    })
    .catch(() => console.info('操作取消'))
}
defineExpose({ validate })
</script>
